package com.hb.trade.server.project.evaluation.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.project.evaluation.dto.EvaluationReviewItemParam;
import com.hb.core.pojo.project.evaluation.dto.EvaluationSecondDTO;
import com.hb.core.pojo.project.evaluation.entity.EvaluationCommitteeMembers;
import com.hb.core.pojo.project.evaluation.entity.EvaluationSecond;
import com.hb.core.pojo.project.evaluation.entity.EvaluationSummary;
import com.hb.core.pojo.project.evaluation.mapper.EvaluationSecondMapper;
import com.hb.core.pojo.project.evaluation.vo.EvaluationResultSummaryVO;
import com.hb.core.pojo.project.file.dto.ReviewItemFirstDto;
import com.hb.core.pojo.project.file.dto.ReviewItemSecondDto;
import com.hb.core.pojo.project.file.entity.ReviewItemSecond;
import com.hb.core.pojo.project.file.mapper.ReviewItemFirstMapper;
import com.hb.core.pojo.project.section.dto.BidSectionTenderDTO;
import com.hb.core.pojo.project.section.mapper.BidSectionTenderMapper;
import com.hb.trade.server.project.evaluation.service.EvaluationCommitteeMembersService;
import com.hb.trade.server.project.evaluation.service.EvaluationSecondService;
import com.hb.trade.server.project.evaluation.service.EvaluationSummaryService;
import com.hb.trade.server.project.file.service.ReviewItemSecondService;
import com.hb.trade.server.project.section.service.raw.BidSectionTenderService;
import org.fzzn.core.model.enums.LogicEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.MsgUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 专家二级评审表 服务实现类
 * </p>
 *
 * @author jinhaolin
 * @since 2022-04-13
 */
@Service
public class EvaluationSecondServiceImpl extends ServiceImpl<EvaluationSecondMapper, EvaluationSecond> implements EvaluationSecondService {

    @Resource
    private ReviewItemFirstMapper reviewItemFirstMapper;
    @Resource
    private BidSectionTenderMapper bidSectionTenderMapper;

    protected final ReviewItemSecondService reviewItemSecondService;
    protected final BidSectionTenderService bidSectionTenderService;
    protected final EvaluationCommitteeMembersService evaluationCommitteeMembersService;
    protected final EvaluationSummaryService evaluationSummaryService;

    public EvaluationSecondServiceImpl(ReviewItemSecondService reviewItemSecondService,
                                       BidSectionTenderService bidSectionTenderService,
                                       EvaluationCommitteeMembersService evaluationCommitteeMembersService,
                                       EvaluationSummaryService evaluationSummaryService) {
        this.reviewItemSecondService = reviewItemSecondService;
        this.bidSectionTenderService = bidSectionTenderService;
        this.evaluationCommitteeMembersService = evaluationCommitteeMembersService;
        this.evaluationSummaryService = evaluationSummaryService;
    }

    @Override
    public List<EvaluationSecond> findBySectionIdAndExpertIdAndSecondId(Long sectionId, Long expertId, Long secondReviewItemId) {
        return baseMapper.findBySectionIdAndExpertIdAndSecondId(sectionId, expertId, secondReviewItemId);
    }

    @Override
    public List<EvaluationSecond> findBySectionIdAndSecondId(Long sectionId, Long secondReviewItemId) {
        return baseMapper.findBySectionIdAndSecondId(sectionId, secondReviewItemId);
    }

    @Override
    public EvaluationResultSummaryVO resultSummaryInfo(EvaluationReviewItemParam evaluationReviewItemParam) {
        Long sectionId = evaluationReviewItemParam.getSectionId();
        Long reviewItemId = evaluationReviewItemParam.getReviewItemId();
        Long expertId = evaluationReviewItemParam.getExpertId();
        String expertName = evaluationReviewItemParam.getExpertName();

        // 组装数据对象
        EvaluationResultSummaryVO evaluationResultSummaryVO = new EvaluationResultSummaryVO();

        // 判断是否已完成汇总
        Integer noSummaryCount = baseMapper.noSummaryCount(sectionId, reviewItemId);
        if (noSummaryCount > 0) {
            // 未汇总
            evaluationResultSummaryVO.setSummaryFlag(0);
        } else {
            // 已汇总
            evaluationResultSummaryVO.setSummaryFlag(1);
        }

        // 根据评审项id获取评审项信息
        ReviewItemSecond reviewItemSecond = reviewItemSecondService.getById(reviewItemId);

        // 确定表头信息
        // 查询未被淘汰的企业的汇总列表
        List<EvaluationSecond> evaluationSecondListNoEliminate = baseMapper.findBySectionIdAndSecondIdAndExpertIdNoEliminate(sectionId, reviewItemId, expertId);
        List<Map<String, Object>> orgHeaderList = new ArrayList<>();
        for (EvaluationSecond evaluationSecond : evaluationSecondListNoEliminate) {
            Map<String, Object> orgMap = new HashMap<>();
            orgMap.put("orgId", evaluationSecond.getOrgId());
            orgMap.put("orgName", evaluationSecond.getOrgName());
            orgHeaderList.add(orgMap);
        }
        evaluationResultSummaryVO.setOrgHeaderList(orgHeaderList);

        // 组装汇总结果map
        List<Map<String, Object>> evaluationResultSummaryList = new ArrayList<>();
        // 查询专家列表
        List<EvaluationCommitteeMembers> evaluationCommitteeMemberList = evaluationCommitteeMembersService.findBySectionId(sectionId);
        for (EvaluationCommitteeMembers evaluationCommitteeMembers : evaluationCommitteeMemberList) {
            Map<String, Object> evaluationResultSummaryMap = new HashMap<>();
            evaluationResultSummaryMap.put("expertId", evaluationCommitteeMembers.getId());
            evaluationResultSummaryMap.put("expertName", evaluationCommitteeMembers.getMemberName());

            // 二级评审项结果
            List<EvaluationSecond> secondList = baseMapper.findBySectionIdAndSecondIdAndExpertIdNoEliminate(sectionId, reviewItemId, evaluationCommitteeMembers.getId());
            for (EvaluationSecond second : secondList) {
                Map<String, Object> evaluationSummaryMap = new HashMap<>();
                evaluationSummaryMap.put("id", second.getId());
                evaluationSummaryMap.put("orgId", second.getOrgId());
                evaluationSummaryMap.put("finalScore", second.getFinalScore());
                evaluationSummaryMap.put("approveFlag", second.getApproveFlag());
                evaluationSummaryMap.put("reviewMode", second.getReviewMode());
                evaluationSummaryMap.put("refuseReason", second.getRefuseReason());

                evaluationResultSummaryMap.put(Long.toString(second.getOrgId()), evaluationSummaryMap);
            }

            evaluationResultSummaryList.add(evaluationResultSummaryMap);
        }

        // 结果汇总
        int reviewMode = reviewItemSecond.getReviewMode();
        Map<String, Object> evaluationResultSummaryMap = new HashMap<>();
        evaluationResultSummaryMap.put("expertId", 0);
        evaluationResultSummaryMap.put("expertName", "汇总");
        List<Long> orgIdList = baseMapper.findOrgListBySectionIdAndSecondIdNoEliminate(sectionId, reviewItemId);
        for (Long orgId : orgIdList) {
            Map<String, Object> evaluationSummaryMap = new HashMap<>();
            evaluationSummaryMap.put("id", 0);
            evaluationSummaryMap.put("orgId", orgId);
            evaluationSummaryMap.put("reviewMode", reviewMode);

            List<EvaluationSecond> evaluationSecondSummaryList = baseMapper.findBySectionIdAndSecondIdAndOrgId(sectionId, reviewItemId, orgId);
            if (evaluationSecondSummaryList.size() == 0) {
                evaluationResultSummaryMap.put(Long.toString(orgId), evaluationSummaryMap);
                continue;
            }

            // 判断是否可对企业汇总
            boolean canSummary = true;
            for (EvaluationSecond evaluationSecond : evaluationSecondSummaryList) {
                if (evaluationSecond.getEvaluationStatus().equals(0)) {
                    canSummary = false;
                    break;
                }
                if (reviewMode == 1) {
                    // 定量
                    if (evaluationSecond.getFinalScore() == null) {
                        canSummary = false;
                        break;
                    }
                } else if (reviewMode == 2) {
                    // 定性
                    if (evaluationSecond.getApproveFlag() == null) {
                        canSummary = false;
                        break;
                    }
                }
            }
            // 不可汇总
            if (!canSummary) {
                evaluationResultSummaryMap.put(Long.toString(orgId), evaluationSummaryMap);
                continue;
            }

            // 汇总结果
            if (reviewMode == 1) {
                // 定量
                List<Double> scoreList = new ArrayList<>();
                for (EvaluationSecond evaluationSecond : evaluationSecondSummaryList) {
                    scoreList.add(evaluationSecond.getFinalScore());
                }
                // 分值排序
                Collections.sort(scoreList, new Comparator<Double>() {
                    @Override
                    public int compare(Double o1, Double o2) {
                        return Double.compare(o1, o2);
                    }
                });

                // 根据不同的评分汇总条件，汇总分数
                int scoreTotalCondition = reviewItemSecond.getScoreTotalCondition();
                Double sumScore = 0.0;
                if (scoreTotalCondition == 1) {
                    // 直接平均
                    sumScore = scoreList.stream().reduce(Double::sum).get();
                } else if (scoreTotalCondition == 2) {
                    // 去掉最高最低再计算平均值
                    scoreList.remove(scoreList.size()-1);
                    scoreList.remove(0);
                    sumScore = scoreList.stream().reduce(Double::sum).get();
                }
                Double summaryScore = sumScore / scoreList.size();
                evaluationSummaryMap.put("finalScore", (double)Math.round(summaryScore * 100) / 100);
            } else if (reviewMode == 2) {
                // 定性
                int summaryApproveFlag = LogicEnum.YES.getCode();
                for (EvaluationSecond evaluationSecond : evaluationSecondSummaryList) {
                    if (evaluationSecond.getApproveFlag().equals(LogicEnum.NO.getCode())) {
                        summaryApproveFlag = LogicEnum.NO.getCode();
                        break;
                    }
                }
                evaluationSummaryMap.put("approveFlag", summaryApproveFlag);
            }

            evaluationResultSummaryMap.put(Long.toString(orgId), evaluationSummaryMap);
        }

        evaluationResultSummaryList.add(evaluationResultSummaryMap);
        evaluationResultSummaryVO.setEvaluationResultSummaryList(evaluationResultSummaryList);

        return evaluationResultSummaryVO;
    }

    @Override
    public Boolean canResultSummary(EvaluationReviewItemParam evaluationReviewItemParam) {
        Long sectionId = evaluationReviewItemParam.getSectionId();
        Long reviewItemId = evaluationReviewItemParam.getReviewItemId();

        Integer noSubmitCount = baseMapper.findNoSubmitCountBySectionIdAndSecondId(sectionId, reviewItemId);
        if (noSubmitCount > 0) {
            return false;
        }

        return true;
    }

    @Override
    public Boolean confirmResultSummary(EvaluationReviewItemParam evaluationReviewItemParam) {
        Long sectionId = evaluationReviewItemParam.getSectionId();
        Long reviewItemId = evaluationReviewItemParam.getReviewItemId();

        baseMapper.editEvaluationStatus(sectionId, reviewItemId, 2);

        return true;
    }

    @Override
    public Boolean recheckResultSummary(Long sectionId, Long reviewItemId) {
        baseMapper.editEvaluationStatus(sectionId, reviewItemId, 1);

        return true;
    }

    /**
     * 初始化评审状态
     *
     * @param sectionId
     * @param secondReviewItemId
     * @return java.lang.Boolean
     * @author tian
     * @date 2022-4-23 11:47
     */
    @Override
    public Boolean initialResultSummary(Long sectionId, Long secondReviewItemId) {
        Integer num = baseMapper.editEvaluationStatus(sectionId, secondReviewItemId, 0);
        return num > 0 ? true : false;
    }

    /**
     * 生成空的汇总对象
     */
    private EvaluationSecond generateEmptySummaryEvaluationObj(BidSectionTenderDTO bidSectionTenderDTO,
                                                               ReviewItemSecond reviewItemSecond,
                                                               Long expertId,
                                                               String expertName) {
        EvaluationSecond evaluationSecond = new EvaluationSecond();
        evaluationSecond.setFileId(bidSectionTenderDTO.getId());
        evaluationSecond.setSecondReviewItemId(reviewItemSecond.getId());
        evaluationSecond.setSectionId(bidSectionTenderDTO.getSectionId());
        evaluationSecond.setExpertId(expertId);
        evaluationSecond.setExpertName(expertName);
        evaluationSecond.setOrgId(bidSectionTenderDTO.getOrgId());
        evaluationSecond.setOrgName(bidSectionTenderDTO.getOrgName());
        evaluationSecond.setReviewMode(reviewItemSecond.getReviewMode());
        evaluationSecond.setEvaluationStatus(0);
        evaluationSecond.setEliminateFlag(LogicEnum.NO.getCode());

        evaluationSecond.buildBaseData(1);
        return evaluationSecond;
    }



    /**
     * 修改专家对应三级评审点的得分和状态
     * @author tian
     * @date 2022-4-20 15:52
     * @param evaluationSecond
     * @return java.lang.Integer
     */
    @Override
    public Integer updateFinalScoreByExpertIdAndSecondReviewItemId(EvaluationSecond evaluationSecond) {
        return baseMapper.updateFinalScoreByExpertIdAndSecondReviewItemId(evaluationSecond);
    }

    @Override
    public Integer updateApproveFlagByExpertIdAndSecondReviewItemId(EvaluationSecond evaluationSecond) {
        return baseMapper.updateApproveFlagByExpertIdAndSecondReviewItemId(evaluationSecond);
    }

    @Override
    public List<EvaluationSecond> listNotEliminate(Long sectionId, Long secondReviewItemId) {
        return baseMapper.listNotEliminate(sectionId,secondReviewItemId);
    }


    /**
     * 查询专家报价信息提交状态
     * @author tian
     * @date 2022-4-20 17:14
     * @param evaluationReviewItemParam
     * @return org.fzzn.core.model.msg.Message<java.util.List<com.hb.core.pojo.project.evaluation.dto.EvaluationSecondDTO>>
     */
    @Override
    public Message<List<EvaluationSecondDTO>> selectOfferReview(EvaluationReviewItemParam evaluationReviewItemParam) {
        List<EvaluationSecondDTO> evaluationSecondDTOList = new ArrayList<>();

        // 查询评委会专家
        List<EvaluationCommitteeMembers> expertList = evaluationCommitteeMembersService.selectCommitteeMembersBySectionId(evaluationReviewItemParam.getSectionId(), null);

        EvaluationSecondDTO evaluationSecondDTO;
        for (EvaluationCommitteeMembers evaluationCommitteeMembers : expertList) {
            // 查询专家是否对报价评审确认
            Integer evaluationStatus = baseMapper.countByEvaluationStatus(evaluationCommitteeMembers.getId(), evaluationReviewItemParam.getSectionId(), evaluationReviewItemParam.getReviewItemId());

            evaluationSecondDTO = new EvaluationSecondDTO();
            evaluationSecondDTO.setExpertName(evaluationCommitteeMembers.getMemberName());
            evaluationSecondDTO.setEvaluationStatus(evaluationStatus);
            evaluationSecondDTOList.add(evaluationSecondDTO);
        }

        return MsgUtil.success(evaluationSecondDTOList);
    }

    @Override
    public List<EvaluationSecond> listEvaluationSecond(Long sectionId, Integer firstReviewItemType) {
        return baseMapper.listEvaluationSecond(sectionId,firstReviewItemType);
    }

    /**
     * 查询最终汇总详情
     *
     * @param evaluationReviewItemParam
     * @return org.fzzn.core.model.msg.Message<java.util.Map>
     * @author tian
     * @date 2022-4-21 15:24
     */
    @Override
    public Message<Map> finalSummaryReview(EvaluationReviewItemParam evaluationReviewItemParam) {
        // 查询二级评审是否全部已汇总
        QueryWrapper<EvaluationSecond> wrapper = EvaluationSecond.wrapper();
        wrapper.eq("section_id", evaluationReviewItemParam.getSectionId())
                .ne("evaluation_status", "2");
        Long reviewSecond = baseMapper.selectCount(wrapper);

        if (reviewSecond != 0) {
            return MsgUtil.fail("当前有未汇总的评审项，请先去汇总");
        }

        Map result = new HashMap();

        // 初评信息
        List<Map> firstList = new ArrayList<>();

        // 详评，报价信息
        List<Map> secondList = new ArrayList<>();

        // 总得分信息信息 （key是orgId value 是得分）
        Map scoreMap = new HashMap();


        // 先获取招标文件评审项信息
        List<ReviewItemFirstDto> reviewItemFirstDtoList = reviewItemFirstMapper.selectReviewItemBySectionId(evaluationReviewItemParam.getSectionId());
        if (CollUtil.isEmpty(reviewItemFirstDtoList)) {
            return MsgUtil.fail("未查询到评审项信息");
        }

        // 获取招标文件都是有哪些一级评审项
        List<Integer> firstReviewItemTypeList = reviewItemFirstDtoList.stream().map(e -> e.getFirstReviewItemType()).collect(Collectors.toList());

        // 查询解密成功的企业
        List<BidSectionTenderDTO> bidSectionTenderList = bidSectionTenderMapper.listDecryptionBidSectionTender(evaluationReviewItemParam.getSectionId(), 1, 1);

        // 如果有初评汇总信息
        if (firstReviewItemTypeList.contains(1)) {

            // 获取详评的一级评审id
            ReviewItemFirstDto reviewItemFirstDto = reviewItemFirstDtoList.get(firstReviewItemTypeList.indexOf(1));
            // 组装初级评审信息
            firstList = assembleFirstReview(result, evaluationReviewItemParam.getSectionId(), reviewItemFirstDto.getId(), bidSectionTenderList);

            // 如果有初评 则说有可能会淘汰企业 所以详评需要查询初评未淘汰的
            List<BidSectionTenderDTO> removeList = new ArrayList<>();
            for (BidSectionTenderDTO bidSectionTenderDTO : bidSectionTenderList) {
                Integer num = baseMapper.countByEliminateFlag(bidSectionTenderDTO.getOrgId(), evaluationReviewItemParam.getSectionId(), null);
                if (num > 0) {
                    removeList.add(bidSectionTenderDTO);
                }
            }

            if(CollUtil.isNotEmpty(removeList)){
                bidSectionTenderList.removeAll(removeList);
            }
        }

        // 如果有详细汇总信息
        if (firstReviewItemTypeList.contains(2)) {
            // 获取详评的一级评审id
            ReviewItemFirstDto reviewItemFirstDto = reviewItemFirstDtoList.get(firstReviewItemTypeList.indexOf(2));

            assembleSecondReview(result, secondList, evaluationReviewItemParam.getSectionId(), reviewItemFirstDto.getId(), bidSectionTenderList, scoreMap);
        }

        // 如果有报价汇总信息
        if (firstReviewItemTypeList.contains(3)) {
            // 获取详评的一级评审id
            ReviewItemFirstDto reviewItemFirstDto = reviewItemFirstDtoList.get(firstReviewItemTypeList.indexOf(3));

            assembleOfferReview(result, secondList, evaluationReviewItemParam.getSectionId(), reviewItemFirstDto.getId(), bidSectionTenderList, scoreMap);
        }

        // 如果存在详细汇总或者是报价汇总  则进行最终得分的计算
        if (firstReviewItemTypeList.contains(2) || firstReviewItemTypeList.contains(3)) {
            finalScoreReview(result, secondList, scoreMap);
        }

        // 查询评标状态
        EvaluationSummary evaluationSummary = evaluationSummaryService.getEvaluationSummaryBySectionId(evaluationReviewItemParam.getSectionId());
        // 评标状态 0，未开始；1，评标中；2，已结束
        result.put("evaluationStatus", evaluationSummary.getEvaluationStatus());

        // 不管初评是否存在 都需要返回一个对象
        result.put("firstList", firstList);
        result.put("secondList", secondList);
        return MsgUtil.success(result);
    }


    /**
     * 组装初级评审信息
     *
     * @param result               主方法返回结果
     * @param reviewItemFirstId    初评id
     * @param reviewItemFirstId    初评id
     * @param bidSectionTenderList 解密的投标人
     * @return java.util.List<java.util.Map>
     * @author tian
     * @date 2022-4-21 17:00
     */
    public List<Map> assembleFirstReview(Map result, Long sectionId, Long reviewItemFirstId, List<BidSectionTenderDTO> bidSectionTenderList) {

        // 初评信息
        List<Map> firstList = new ArrayList<>();

        // 查询二级评审点汇总
        List<ReviewItemSecondDto> reviewItemSecondDtoList = reviewItemSecondService.selectReviewItemSecondList(reviewItemFirstId);

        // 查询每家企业的初评汇总信息
        Map orgFirst;
        for (BidSectionTenderDTO bidSectionTenderDTO : bidSectionTenderList) {
            orgFirst = new HashMap();
            orgFirst.put("orgId", bidSectionTenderDTO.getOrgId());
            orgFirst.put("orgName", bidSectionTenderDTO.getOrgName());

            // 结论
            Integer approveFlagSummary = 1;
            for (ReviewItemSecondDto reviewItemSecondDto : reviewItemSecondDtoList) {
                // 查询当前企业是否合格
                Integer num = baseMapper.countByApproveFlag(bidSectionTenderDTO.getOrgId(), sectionId, reviewItemSecondDto.getId());
                // 是否合格（1，合格，2，不合格）
                Integer approveFlag = num > 0 ? 2 : 1;

                // 初评只要一项不合格 结论就是不合格
                if (approveFlag.equals(2)) {
                    approveFlagSummary = 2;
                }

                orgFirst.put(reviewItemSecondDto.getId(), approveFlag);
            }

            orgFirst.put(0, approveFlagSummary);
            firstList.add(orgFirst);
        }

        ReviewItemSecondDto reviewItemSecondDtoSummary = new ReviewItemSecondDto();
        reviewItemSecondDtoSummary.setId(0L);
        reviewItemSecondDtoSummary.setSecondReviewItemName("结论");
        reviewItemSecondDtoList.add(reviewItemSecondDtoSummary);

        result.put("firstItemNameList", reviewItemSecondDtoList);

        return firstList;
    }


    /**
     * 组装详细评审信息
     *
     * @param result               主方法返回结果
     * @param reviewItemFirstId    详细id
     * @param sectionId    标段id
     * @param bidSectionTenderList 未淘汰的投标人
     * @param scoreMap             总得分信息信息 （key是orgId value 是得分）
     * @return java.util.List<java.util.Map>
     * @author tian
     * @date 2022-4-21 17:00
     */
    public void assembleSecondReview(Map result, List<Map> secondList, Long sectionId, Long reviewItemFirstId, List<BidSectionTenderDTO> bidSectionTenderList, Map scoreMap) {

        // 查询详评评审点汇总
        List<ReviewItemSecondDto> reviewItemSecondDtoList = reviewItemSecondService.selectReviewItemSecondList(reviewItemFirstId);

        // 查询每家企业的初评汇总信息
        Map orgFirst;
        for (BidSectionTenderDTO bidSectionTenderDTO : bidSectionTenderList) {
            orgFirst = new HashMap(); // 前端展示的信息
            orgFirst.put("orgId", bidSectionTenderDTO.getOrgId());
            orgFirst.put("orgName", bidSectionTenderDTO.getOrgName());

            BigDecimal sumScore = new BigDecimal("0");
            for (ReviewItemSecondDto reviewItemSecondDto : reviewItemSecondDtoList) {
                // 查询当前评审项 每个的打分
                QueryWrapper<EvaluationSecond> evaluationSecondQueryWrapper = new QueryWrapper<>();
                evaluationSecondQueryWrapper.lambda().eq(EvaluationSecond::getSecondReviewItemId, reviewItemSecondDto.getId())
                        .eq(EvaluationSecond::getSectionId, sectionId)
                        .eq(EvaluationSecond::getOrgId, bidSectionTenderDTO.getOrgId());

                List<EvaluationSecond> evaluationSecondList = baseMapper.selectList(evaluationSecondQueryWrapper);
                // 专家报价的集合
                List<Double> finalScoreList = evaluationSecondList.stream().sorted(Comparator.comparing(EvaluationSecond::getFinalScore)).map(EvaluationSecond::getFinalScore).collect(Collectors.toList());

                // 判断当前评分汇总的类型  评分汇总条件 1：直接平均  2：去掉最高最低再计算平均值
                Integer scoreTotalCondition = reviewItemSecondDto.getScoreTotalCondition();
                if (null != scoreTotalCondition && scoreTotalCondition.equals(2)) {
                    // 如果大于两个人则却去掉最高和最低
                    if (finalScoreList.size() > 2) {
                        finalScoreList.remove(0);
                        finalScoreList.remove(finalScoreList.size()-1);
                    }
                }
                // 求评价值
                BigDecimal sum = new BigDecimal("0");
                BigDecimal ave =  new BigDecimal("0");
                if (CollUtil.isNotEmpty(finalScoreList)) {
                    for (Double finalScore : finalScoreList) {
                        sum = sum.add(new BigDecimal(finalScore)).setScale(3, BigDecimal.ROUND_HALF_UP);
                    }
                    // 当前评审项目的平均值
                    ave = sum.divide(new BigDecimal(finalScoreList.size()), 2, BigDecimal.ROUND_HALF_UP);
                }

                orgFirst.put(reviewItemSecondDto.getId(), ave.toString());

                // 实时计算得分
                sumScore = sumScore.add(ave).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            secondList.add(orgFirst);

            scoreMap.put(bidSectionTenderDTO.getOrgId(), sumScore.toString());
        }

        result.put("detailedItemNameList", reviewItemSecondDtoList);
    }


    /**
     * 组装报价评审信息
     *
     * @param result               主方法返回结果
     * @param secondList           详细评审汇总信息
     * @param sectionId            标段id
     * @param reviewItemFirstId    报价id
     * @param bidSectionTenderList 未淘汰的投标人
     * @param scoreMap             总得分信息信息 （key是orgId value 是得分）
     * @return java.util.List<java.util.Map>
     * @author tian
     * @date 2022-4-21 17:00
     */
    public List<Map> assembleOfferReview(Map result, List<Map> secondList, Long sectionId, Long reviewItemFirstId, List<BidSectionTenderDTO> bidSectionTenderList, Map scoreMap) {

        List<ReviewItemSecondDto> sumReviewItemSecondDtoList = new ArrayList<>();
        // 详细评审点和报价评审点需要合并
        if (result.containsKey("detailedItemNameList")) {
            sumReviewItemSecondDtoList = (List<ReviewItemSecondDto>) result.get("detailedItemNameList");
        }

        // 查询详评评审点汇总
        List<ReviewItemSecondDto> reviewItemSecondDtoList = reviewItemSecondService.selectReviewItemSecondList(reviewItemFirstId);

        // 如果大于0 说明有详评的信息
        if (secondList.size() > 0) {
            for (Map secondReviewInfo : secondList) {
                Long orgId = (Long) secondReviewInfo.get("orgId");

                BigDecimal sum = new BigDecimal((String) scoreMap.get(orgId));

                // 查询当前公司的报价得分
                QueryWrapper<EvaluationSecond> evaluationSecondQueryWrapper = new QueryWrapper<>();
                evaluationSecondQueryWrapper.lambda().eq(EvaluationSecond::getSecondReviewItemId, reviewItemSecondDtoList.get(0).getId())
                        .eq(EvaluationSecond::getSectionId, sectionId)
                        .eq(EvaluationSecond::getOrgId, orgId);

                List<EvaluationSecond> evaluationSecondList = baseMapper.selectList(evaluationSecondQueryWrapper);

                // 因为报价只有组长可以打分 其他人都是用的组长的信息
                EvaluationSecond evaluationSecond = evaluationSecondList.get(0);

                BigDecimal offerScale = new BigDecimal(evaluationSecond.getFinalScore()).setScale(2, BigDecimal.ROUND_HALF_UP);

                // 报价评审得分
                secondReviewInfo.put(reviewItemSecondDtoList.get(0).getId(), offerScale.toString());

                // 计算总得分并重新放回
                sum = sum.add(offerScale).setScale(2, BigDecimal.ROUND_HALF_UP);
                scoreMap.put(orgId, sum.toString());
            }
        } else {
            // 查询每家企业的初评汇总信息
            Map orgOffer;
            // 如果没有详细评审 则直接去查询报价评审
            for (BidSectionTenderDTO bidSectionTenderDTO : bidSectionTenderList) {
                orgOffer = new HashMap();
                orgOffer.put("orgId", bidSectionTenderDTO.getOrgId());
                orgOffer.put("orgName", bidSectionTenderDTO.getOrgName());

                // 查询当前公司的报价得分
                QueryWrapper<EvaluationSecond> evaluationSecondQueryWrapper = new QueryWrapper<>();
                evaluationSecondQueryWrapper.lambda().eq(EvaluationSecond::getSecondReviewItemId, reviewItemSecondDtoList.get(0).getId())
                        .eq(EvaluationSecond::getSectionId, sectionId)
                        .eq(EvaluationSecond::getOrgId, bidSectionTenderDTO.getOrgId());

                List<EvaluationSecond> evaluationSecondList = baseMapper.selectList(evaluationSecondQueryWrapper);

                // 因为报价只有组长可以打分 其他人都是用的组长的信息
                EvaluationSecond evaluationSecond = evaluationSecondList.get(0);

                BigDecimal finalScore = new BigDecimal(evaluationSecond.getFinalScore()).setScale(2, BigDecimal.ROUND_HALF_UP);

                // 报价评审得分
                orgOffer.put(reviewItemSecondDtoList.get(0).getId(), finalScore.toString());

                secondList.add(orgOffer);

                // 计算总得分并重新放回
                scoreMap.put(bidSectionTenderDTO.getOrgId(), finalScore.toString());
            }
        }

        // 详细评审点和报价评审点需要合并
        ReviewItemSecondDto reviewItemSecondDto = reviewItemSecondDtoList.get(0);
        reviewItemSecondDto.setSecondReviewItemName("报价得分");
        sumReviewItemSecondDtoList.add(reviewItemSecondDto);

        result.put("detailedItemNameList", sumReviewItemSecondDtoList);

        return secondList;
    }


    /**
     * 计算排名
     *
     * @param result     主方法返回结果
     * @param secondList 详细评审汇总信息
     * @param scoreMap   总得分信息信息 （key是orgId value 是得分）
     * @author tian
     * @date 2022-4-21 19:26
     */
    public void finalScoreReview(Map result, List<Map> secondList, Map scoreMap) {
        List<ReviewItemSecondDto> sumReviewItemSecondDtoList = new ArrayList<>();
        // 详细评审点和报价评审点需要合并
        if (result.containsKey("detailedItemNameList")) {
            sumReviewItemSecondDtoList = (List<ReviewItemSecondDto>) result.get("detailedItemNameList");
        }

        for (Map secondReviewInfo : secondList) {
            Long orgId = (Long) secondReviewInfo.get("orgId");

            BigDecimal finalScore = new BigDecimal((String)scoreMap.get(orgId));

            secondReviewInfo.put(0L, finalScore.toString());
        }

        // 计算排名
        lowestPriceRanking(secondList);

        // 添加最终得分
        ReviewItemSecondDto finalScoreReview = new ReviewItemSecondDto();
        finalScoreReview.setId(0L);
        finalScoreReview.setSecondReviewItemName("最终得分");
        sumReviewItemSecondDtoList.add(finalScoreReview);

        // 添加最终得分
        ReviewItemSecondDto ranking = new ReviewItemSecondDto();
        ranking.setId(1L);
        ranking.setSecondReviewItemName("排名");
        sumReviewItemSecondDtoList.add(ranking);

        result.put("detailedItemNameList", sumReviewItemSecondDtoList);
    }


    /**
     * 排名
     *
     * @param legalDtoList
     */
    private void lowestPriceRanking(List<Map> legalDtoList) {
        // 0L 是Map 中最终得分 的key
        // 按照最终得分排序
        Comparator<Map> comparator = new Comparator<Map>() {
            @Override
            public int compare(Map o1, Map o2) {
                BigDecimal one = new BigDecimal((String)o1.get(0L));
                BigDecimal two = new BigDecimal((String)o2.get(0L));
                if (one.compareTo(two) == 1) {
                    return -1;
                } else if (one.compareTo(two) == 0) {
                    return 0;
                } else {
                    return 1;
                }
            }
        };

        Collections.sort(legalDtoList, comparator);
        // 分数相同 ，排名 1 2 3 4，改为 1 2 2 4.
        int index = 0;// 排名
        int no = 0;//去重
        BigDecimal lastScore = new BigDecimal(9999);// 最近一次的分（设置一个最大值）
        for (int i = 0; i < legalDtoList.size(); i++) {
            Map s = legalDtoList.get(i);
            BigDecimal finalScore = new BigDecimal((String)s.get(0L));
            if (lastScore.compareTo(finalScore) == 1) { // 如果得分和上一名的得分相同,那么排名+1
                lastScore = finalScore;
                index = index + 1 + no;
                no = 0;
            } else {
                no++;
            }
            s.put(1L, index);
        }
    }


    /**
     * 查询专家是否对报价评审确认
     * @author tian
     * @date 2022-4-20 17:19
     * @param expertId
     * @param sectionId
     * @param secondReviewItemId
     * @return java.lang.Integer
     */
    @Override
    public Integer countByEvaluationStatus(Long expertId, Long sectionId, Long secondReviewItemId) {
        return baseMapper.countByEvaluationStatus(expertId, sectionId, secondReviewItemId);
    }

    @Override
    public Boolean saveOrgEliminateStatus(Long sectionId, Long reviewItemId, List<Long> idList) {
        if (idList.size() > 0) {
            baseMapper.updateOrgEliminateStatus(sectionId, reviewItemId, idList);
        }

        return true;
    }

    @Override
    public Boolean cancelOrgEliminateStatus(Long sectionId, Long reviewItemId) {
        baseMapper.cancelOrgEliminateStatus(sectionId, reviewItemId);
        return true;
    }

    @Override
    public int getEvaluationStatusCount(Long sectionId, List<Integer> evaluationStatusList) {
        QueryWrapper<EvaluationSecond> wrapper = EvaluationSecond.wrapper();
        wrapper.eq("section_id", sectionId)
                .in("evaluation_status", evaluationStatusList);
        Long reviewSecond = baseMapper.selectCount(wrapper);
        return Math.toIntExact(reviewSecond);
    }
}
